﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace SmartBlast
{
    public partial class frmComponents : Form
    {
        private static string TABLE_NAME = "Components";
        private static string[] HEADERS = new string[] { "Serial Number", "Name","Description", "Quality", "Quantity In Stock", "Threshold"};
        private static string[] FIELD_NAMES = new string[] { "Serial_Number", "Name", "Description", "Quality", "Quantity", "Min_Quantity" };
        private string[] fields;
        private DataTable compsDataTable;
        private bool editable = false;
        private DataBase_BUS databaseBUS;
        private Main main;

        public frmComponents(Main main)
        {
            InitializeComponent();
            databaseBUS = DataBase_BUS.getInstance();
            this.main = main;
           
        }

        private void btn_search_Click(object sender, EventArgs e)
        {
            collectFields();
            compsDataTable = databaseBUS.selectRecrordFromTable(TABLE_NAME, FIELD_NAMES, fields);
            refresh();
        }

        private void btn_add_Click(object sender, EventArgs e)
        {
            if (!noFieldsAreBlank())
                MessageBox.Show("\nPlease input all fields", "Missing Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            else if (!(IsQuantityAboveThreshold(txtQuantity.Text, txtThreshold.Text)))
            {
                MessageBox.Show("\nInitial quantity cannot exceed below threshold!", "Invalid fields", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                collectFields();
                try
                {
                   databaseBUS.insertRecordIntoTable(TABLE_NAME, fields);
                    clearTextBoxes();
                    showAll();
                }
                catch
                {
                    gridComps.Visible = false;
                    lbl_NoResults.Visible = true;
                    lbl_NoResults.Text = "There is a component with the same Serial Number. \n Please select another code";
                }

            }
        }

        private void btn_Clear_Click(object sender, EventArgs e)
        {
            clearTextBoxes();
        }

        private void btn_showAll_Click(object sender, EventArgs e)
        {
            showAll();
        }

        private void collectFields()
        {

            fields = new string[] { txtSN.Text, "'" + txtName.Text + "'","'" + txtDesc.Text + "'",
                cmbQuality.Text, txtQuantity.Text, txtThreshold.Text };
        }

        private Boolean noFieldsAreBlank()
        {
            return (txtSN.Text != "" && txtName.Text != "" && txtDesc.Text != "" && txtQuantity.Text != "" && txtThreshold.Text != "" && cmbQuality.SelectedIndex != -1);
        }

        private void clearTextBoxes()
        {
            txtSN.Text = txtName.Text = txtDesc.Text = txtQuantity.Text = txtThreshold.Text = "";
            cmbQuality.SelectedIndex = -1;  
        }

        private void showAll()
        {
            compsDataTable = databaseBUS.selectRecrordFromTable(TABLE_NAME, null, null);
            refresh();
        }


        private void refresh()
        {
            if (compsDataTable.Rows.Count == 0)
            {
                gridComps.Visible = false;
                lbl_NoResults.Visible = true;
            }
            else
            {
                lbl_NoResults.Visible = false;
                gridComps.Visible = true;
                gridComps.DataSource = compsDataTable;
                gridComps.Columns[3].ReadOnly = true; 
                for (int i = 3; i < gridComps.ColumnCount; i++)
                    gridComps.Columns[i].HeaderText = HEADERS[i - 3];
            }
        }

        private void gridComps_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            string id = ((System.Windows.Forms.DataGridView)(sender)).CurrentRow.Cells[3].Value.ToString();
            int index = (((System.Windows.Forms.DataGridView)(sender)).CurrentCell).ColumnIndex;
            

            if (index == 0) //click on "edit"
            {
                ((System.Windows.Forms.DataGridView)(sender)).CurrentRow.DefaultCellStyle.ForeColor = Color.Red;
                editable = true;
            }

            else if (index == 1 && editable) //click on "save"
            {
                string name = ((System.Windows.Forms.DataGridView)(sender)).CurrentRow.Cells[4].Value.ToString();
                string description = ((System.Windows.Forms.DataGridView)(sender)).CurrentRow.Cells[5].Value.ToString();
                string quality = ((System.Windows.Forms.DataGridView)(sender)).CurrentRow.Cells[6].Value.ToString();
                string quantity = ((System.Windows.Forms.DataGridView)(sender)).CurrentRow.Cells[7].Value.ToString();
                string threshold = ((System.Windows.Forms.DataGridView)(sender)).CurrentRow.Cells[8].Value.ToString();

                fields = new string[] { id, "'" + name + "'", "'"+description+"'",quality, quantity, threshold};

                databaseBUS.updateRecordInTable(TABLE_NAME, FIELD_NAMES, fields, FIELD_NAMES[0], fields[0]);

                if(IsQuantityAboveThreshold(quantity, threshold)) {
                    MessageBox.Show("The component was successfully updated");
                }
                else {
                    MessageBox.Show("\nPlease note that the updated component's quantity is below its threshold!!!", "Attention", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                showAll();
                editable = false;
            }

            else if (index == 2) //click on "delete"
            {
                DialogResult dialogResult = MessageBox.Show("Are you sure you want to delete the component?", "Delete", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    databaseBUS.deleteRecordFromTable(TABLE_NAME, FIELD_NAMES[0], id);
                    MessageBox.Show("The component was successfully deleted");
                }
                                
                showAll();
            }
        }

        private void txtSN_TextChanged(object sender, EventArgs e)
        {
            int sn;
            bool success = int.TryParse(txtSN.Text, out sn);
            String prevText = txtSN.Text.Substring(0, Math.Max(0, txtSN.Text.Length - 1));
            if (!success)
            {
                txtSN.Text = prevText;
            }
            else
            {
                txtSN.Text = sn.ToString();
            }
        }

        private void txtThreshold_TextChanged(object sender, EventArgs e)
        {
            int threshold;
            bool success = int.TryParse(txtThreshold.Text, out threshold);
            String prevText = txtThreshold.Text.Substring(0, Math.Max(0, txtThreshold.Text.Length - 1));
            if (!success)
            {
                txtThreshold.Text = prevText;
            }
            else
            {
                txtThreshold.Text = threshold.ToString();
            }
        }


        private void btn_exit_Click(object sender, EventArgs e)
        {
            main.Show();
            this.Hide();
        }

        

        private void txtfld_compQuantity_TextChanged(object sender, EventArgs e)
        {
            int quantity;
            bool success = int.TryParse(txtQuantity.Text, out quantity);
            String prevText = txtQuantity.Text.Substring(0, Math.Max(0, txtQuantity.Text.Length - 1));
            if (!success)
            {
                txtQuantity.Text = prevText;
            }
            else
            {
                txtQuantity.Text = quantity.ToString();
            }
        }

        private bool IsQuantityAboveThreshold(String quantity, string threshold)
        {
            int quantityNum;
            int.TryParse(quantity, out quantityNum);

            int thresholdNum;
            int.TryParse(threshold, out thresholdNum);

            return (quantityNum > thresholdNum);
        }

        private void textBox1_Enter(object sender, EventArgs e)
        {
            string input = Microsoft.VisualBasic.Interaction.InputBox("Input component Description:", "Component Description", "", -1, -1);
            
            txtDesc.Text = input;
        }

        private void frmComponents_Load(object sender, EventArgs e)
        {
            this.CenterToScreen();
            cmbQuality.SelectedIndex = -1;
        }






    }
}
